# Configuration.py
# Copyright (C) otacon 2010 <orfeo18@gmail.com>
# 
# AdSense-Monitor is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# AdSense-Monitor is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

import ConfigParser
import Path
import gobject
import os
import inspect
import shutil
import sys
import copy
from Report import ReportRow

class Configuration(gobject.GObject):

    __gsignals__ = {
    'config-changed' :
            (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                (gobject.TYPE_PYOBJECT,
                 )),
    }
    
    defaults = {
        'sound_clicks' : False,
        'sound_file' : str(os.path.join('.','data','notification.wav')),
        'show_report_time' : True,
        'show_clicks' : True,
        'sound_report_time' : False,
        'save_password' : True,
        'notify_impressions' : True,
        'notify_ecpm' : False,
        'auto_update' : True,
        'show_popups' : True,
        'notify_ctr' : False,
        'show_ecpm' : True,
        'update_rate' : 5.0,
        'update_tooltip' : True,
        'notify_clicks' : True,
        'notify_report_time' : False,
        'show_ctr' : True,
        'username' : '',
        'show_earnings' : True,
        'sound_impressions' : False,
        'password' : '',
        'notify_earnings' : True,
        'sound_earnings' : True,
        'sound_ecpm' : False,
        'show_impressions' : True,
        'play_sound' : True,
        'sound_ctr' : False,
        'auto_start' : False,
        'detect_proxy' : True,
        'proxy_server' : '',
        'proxy_port' : 0
    }
        
    
    def __init__( self ):
        gobject.GObject.__init__(self)
        self.config = ConfigParser.SafeConfigParser()
        
        if self._config_file_exists():
            self.config.read(Path.PROFILE_PATH)
        
        else:
            self.config.add_section('Preferences')
            self.config.add_section('Report')
            self.config.set( 'Report' , 'Earnings', '0' )
            self.config.set( 'Report' , 'eCPM', '0' )
            self.config.set( 'Report' , 'Impressions', '0' )
            self.config.set( 'Report' , 'Clicks', '0' )
            self.config.set( 'Report' , 'CTR', '0' )
            self.config.set( 'Report' , 'Report Day', '2000-01-01' )

    def _config_file_exists( self ):
        if not os.path.exists(Path.CONFIG_PATH):
            os.mkdir(Path.CONFIG_PATH)
            
        if not os.path.exists(Path.ADSENSE_PATH):
            os.mkdir(Path.ADSENSE_PATH)

        if not os.path.exists(Path.PROFILE_PATH):
            exists = False
        else:
            exists = True

        return exists
        
    def set_preferences(self , pref_dict):
        for key in pref_dict:
            self.config.set('Preferences',key,str(pref_dict[key]))
        
        if 'password' in pref_dict and 'save_password' in pref_dict:
                if not pref_dict['save_password']:
                    self.config.set('Preferences','password','')
        
        self.emit('config-changed',pref_dict)
        self.write_configurations()

    def get_preference(self, name):
        if name == 'proxy_server':
            pass
        elif name == 'proxy_port':
            pass

        elif self.config.has_option('Preferences',name):
            value = self.config.get('Preferences',name)
            if value == 'True' or value == 'False':
                return value == 'True'
            try: 
                return float(value)
            except:
                return value
        else: 
            return Configuration.defaults[name]

    def get_report( self ):    
        try:
            earnings = float(self.config.get( 'Report' , 'Earnings'))
            ecpm = float(self.config.get( 'Report' , 'eCPM'))
            impressions = int(self.config.get( 'Report' , 'Impressions'))
            clicks = int(self.config.get( 'Report' , 'Clicks'))
            ctr = float(self.config.get( 'Report' , 'CTR'))
            day = self.config.get( 'Report' , 'Report Day')
            date = day.split('-')
            year = int(date[0])
            month = int(date[1])
            day = int(date[2])
            report_row = ReportRow()
            report_row.set_day(year, month, day)
            report_row.set_impressions(impressions)
            report_row.set_clicks(clicks)
            report_row.set_ctr(ctr)
            report_row.set_ecpm(ecpm)
            report_row.set_earnings(earnings)

            return report_row

        except ConfigParser.NoOptionError:
            return None

    def set_report( self , report ):
        self.config.set( 'Report' , 'Earnings', str(report.get_earnings()) )
        self.config.set( 'Report' , 'eCPM', str(report.get_ecpm()) )
        self.config.set( 'Report' , 'Impressions', str(report.get_impressions()) )
        self.config.set( 'Report' , 'Clicks', str(report.get_clicks()) )
        self.config.set( 'Report' , 'CTR', str(report.get_ctr()) )
        day = report.get_day()
        self.config.set( 'Report' , 'Report Day', str(report.get_day()) )
        self.write_configurations()
        return True        

    def get_options_dict(self):
        options = {}
        for option in self.config.options('Preferences'):
            options[option] = self.get_preference(option)
        return options
    
    def write_configurations(self):
        configfile = open( Path.PROFILE_PATH , 'w')
        self.config.write(configfile)
        return

def add_method(cls,i,value_type):
    get_ = None

    if value_type is bool:
        def get_( self ):
            return self.config.get('Preferences',i) == 'True'

    elif value_type is float or value_type is int:
        def get_( self ):
            return float(self.config.get('Preferences',i))

    elif value_type is str:
        def get_( self ):
            return self.config.get('Preferences',i)

    def set_(self,name):
        self.config.set('Preferences',i,str(name))

    if get_:
        setattr(Configuration,'get_'+i,get_)
        setattr(Configuration,'set_'+i,set_)
    
for i in Configuration.defaults:
    add_method(Configuration,i,type(Configuration.defaults[i]))
